package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.AppUserVip;
import com.ruoyi.app.domain.bo.AppUserVipBo;
import com.ruoyi.app.domain.bo.AppVipCardBo;
import com.ruoyi.app.domain.vo.*;
import com.ruoyi.app.mapper.AppUserVipMapper;
import com.ruoyi.app.service.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * APP用户VIPService业务层处理
 *
 * @author heike
 * @date 2025-03-16
 */
@RequiredArgsConstructor
@Service
public class AppUserVipServiceImpl implements IAppUserVipService {

    private final AppUserVipMapper baseMapper;
    private final IAppVipCardService appVipCardService;
    private final IAppVipTypeService iAppVipTypeService;
    private final IAppVipOrderService iAppVipOrderService;


    /**
     * 查询APP用户VIP
     */
    @Override
    public AppUserVipVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }


    /**
     * 查询APP用户VIP
     */
    @Override
    public AppUserVipVo queryByUserId(Long userId) {
        LambdaQueryWrapper<AppUserVip> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppUserVip::getUserId, userId);
        return baseMapper.selectVoOne(wrapper);
    }

    /**
     * 查询APP用户VIP列表
     */
    @Override
    public TableDataInfo<AppUserVipVo> queryPageList(AppUserVipBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppUserVip> lqw = buildQueryWrapper(bo);
        Page<AppUserVipVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP用户VIP列表
     */
    @Override
    public List<AppUserVipVo> queryList(AppUserVipBo bo) {
        LambdaQueryWrapper<AppUserVip> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppUserVip> buildQueryWrapper(AppUserVipBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppUserVip> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppUserVip::getUserId, bo.getUserId());
        lqw.eq(bo.getEndTime() != null, AppUserVip::getEndTime, bo.getEndTime());
        return lqw;
    }

    /**
     * 新增APP用户VIP
     */
    @Override
    public Boolean insertByBo(AppUserVipBo bo) {
        AppUserVip add = BeanUtil.toBean(bo, AppUserVip.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改APP用户VIP
     */
    @Override
    public Boolean updateByBo(AppUserVipBo bo) {
        AppUserVip update = BeanUtil.toBean(bo, AppUserVip.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改APP用户VIP
     */
    public Boolean updateByVo(AppUserVipVo vo) {
        AppUserVip update = BeanUtil.toBean(vo, AppUserVip.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public String userVip(Long userId) {
        String endTime = null;
        LambdaQueryWrapper<AppUserVip> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppUserVip::getUserId, userId);
        AppUserVipVo appUserVipVo = baseMapper.selectVoOne(wrapper);
        if (Objects.nonNull(appUserVipVo)) {
            if (appUserVipVo.getEndTime().compareTo(System.currentTimeMillis()) > 0) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                endTime = simpleDateFormat.format(new Date(appUserVipVo.getEndTime()));
            }
        }
        return endTime;
    }

    @Override
    public AppUserVipVo userVipId(Long userId) {
        LambdaQueryWrapper<AppUserVip> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppUserVip::getUserId, userId);
        AppUserVipVo appUserVipVo = baseMapper.selectVoOne(wrapper);
        if (Objects.nonNull(appUserVipVo)) {
            if (appUserVipVo.getEndTime().compareTo(System.currentTimeMillis()) > 0) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String format = simpleDateFormat.format(new Date(appUserVipVo.getEndTime()));
                appUserVipVo.setVipExpireTime(format);
                return appUserVipVo;
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addVipTime(AppVipOrderVo vipOrder, String tradeNo, String outTradeNo, String payType) {
        AppVipTypeVo appVipTypeVo = iAppVipTypeService.queryById(vipOrder.getVipId());
        AppUserVipVo vipVo = queryByUserId(vipOrder.getUserId());
        if (ObjectUtils.isEmpty(vipVo)) {
            AppUserVipBo appUserVip = new AppUserVipBo();
            appUserVip.setUserId(vipOrder.getUserId());
            //86400L = 1天秒数
            long endTime = System.currentTimeMillis() + appVipTypeVo.getDay() * 86400L * 1000L;
            appUserVip.setEndTime(endTime);
            insertByBo(appUserVip);
        } else {
            //大于当前时间，说明VIP未到期，增加时间
            long endTime = 0;
            if (vipVo.getEndTime().compareTo(System.currentTimeMillis()) > 0) {
                endTime = vipVo.getEndTime() + appVipTypeVo.getDay() * 86400L * 1000L;
            } else {
                endTime = System.currentTimeMillis() + appVipTypeVo.getDay() * 86400L * 1000L;
            }
            vipVo.setEndTime(endTime);
            updateByVo(vipVo);
        }
        vipOrder.setPayType(payType);
        vipOrder.setStatus(Constants.FAIL);
        if (StringUtils.equals(payType, "integral")) {
            vipOrder.setType(Constants.THREE);
        } else {
            vipOrder.setType(Constants.FAIL);
        }
        iAppVipOrderService.updateByVo(vipOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addVipTime(AppVipCardVo appVipCardVo, Long userId, Integer day) {
        AppUserVipVo vipVo = queryByUserId(userId);
        if (Objects.isNull(vipVo)) {
            AppUserVipBo appUserVip = new AppUserVipBo();
            appUserVip.setUserId(userId);
            //86400L = 1天秒数
            long endTime = System.currentTimeMillis() + day * 86400L * 1000L;
            appUserVip.setEndTime(endTime);
            insertByBo(appUserVip);
        } else {
            long endTime = 0;
            if (vipVo.getEndTime().compareTo(System.currentTimeMillis()) > 0) {
                endTime = vipVo.getEndTime() + day * 86400L * 1000L;
            } else {
                endTime = System.currentTimeMillis() + day * 86400L * 1000L;
            }
            vipVo.setEndTime(endTime);
            updateByVo(vipVo);
        }
        AppVipCardBo appVipCardBo = new AppVipCardBo();
        appVipCardBo.setCardId(appVipCardVo.getCardId());
        appVipCardBo.setUserId(userId);
        appVipCardBo.setStaus(Constants.FAIL);
        appVipCardBo.setUseTime(DateUtils.getNowDate());
        appVipCardService.updateByBo(appVipCardBo);
    }


    @Override
    public void addFreeVipTime(Long userId, Integer day) {
        AppUserVipVo vipVo = queryByUserId(userId);
        if (Objects.isNull(vipVo)) {
            AppUserVipBo appUserVip = new AppUserVipBo();
            appUserVip.setUserId(userId);
            //86400L = 1天秒数
            long endTime = System.currentTimeMillis() + day * 86400L * 1000L;
            appUserVip.setEndTime(endTime);
            insertByBo(appUserVip);
        } else {
            //大于当前时间，说明VIP未到期，增加时间
            long endTime = 0;
            if (vipVo.getEndTime().compareTo(System.currentTimeMillis()) > 0) {
                endTime = vipVo.getEndTime() + day * 86400L * 1000L;
            } else {
                endTime = System.currentTimeMillis() + day * 86400L * 1000L;
            }
            vipVo.setEndTime(endTime);
            updateByVo(vipVo);
        }
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppUserVip entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP用户VIP
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean deleteWithValidById(Long id) {
        return baseMapper.deleteById(id) > 0;
    }
}
